
import com.jfinal.kit.TimeKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.druid.DruidPlugin;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        DruidPlugin dp = new DruidPlugin("jdbc:mysql://192.168.10.64:8059/test", "root", "ldcroot");
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
        CollectIUDSQLFilter filter = new CollectIUDSQLFilter();
        dp.addFilter(filter);
        dp.start();
        arp.start();
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                Db.update("insert INTO test (`name`,`age`) values (?,?)","李四",2);
                int i = Db.update("insert INTO test (`name`,`age`) values (?,?)","张三",1);
                return i == 2;
            }
        });
        Db.update("insert INTO test (`name`,`age`) values (?,?)","王五",2);
        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                int i = Db.update("insert INTO test (`name`,`age`) values (?,?)","李四",3);
                i += Db.update("insert INTO test (`name`,`age`) values (?,?)","张三",4);
                return i == 2;
            }
        });
        Db.update("update test set age = 1 where name = '张三'");
        Db.save("test",new Record().set("name","一").set("age",1));
        Db.delete("delete from test where name = ?","王五");

        try {
            Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    Db.save("test","id",new Record().set("name","test1").set("age",1));
                    Db.save("test","id",new Record().set("id",1).set("name","test").set("age",1));
                    return false;
                }
            });
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
        System.out.println();
        System.out.println("collect sql list:"); // 收集到的sql
        System.out.println("collect auto sql list:");
        for (String sql:CollectIUDSQLFilter.autoSql){
            System.out.println(sql);
        }
        System.out.println("collect tx sql list: ");
        for (String key:CollectIUDSQLFilter.txSqlMapList.keySet()){
            String[] txInfo = key.split("_");
            System.out.println("time:" + TimeKit.format(new Date(Long.valueOf(txInfo[0])),"yyyy-MM-dd HH:mm:ss") + " conn_id:" + txInfo[1]);
            List<String> txSqlList = CollectIUDSQLFilter.txSqlMapList.get(key);
            for (String sql:txSqlList){
                System.out.println(sql);
            }
        }
        System.out.println();
    }
}
